class LoginController < ApplicationController
  def login
    if request.post?
      #process login request
      email_address = params[:txtEmailAddress]
      password = params[:txtPassword]

      login_user = User.authenticate(email_address, password)
      
      if login_user.nil?
        redirect_to :action => "login"
        flash[:notice] = "Unknown user or invalid password"
      else
        set_session_variables(login_user)
        if params[:chkRememberMe] == "on"
          cookies[:login] = {:value => login_user.email_address, :expires => 20.days.from_now }
        end
        redirect_to :controller => "patients", :action => "index"
      end
    else
      # if its a normal request, check for valid cookie or session
      if cookies[:login].nil? && session[:user_id].nil?
        # no cookie found or session found => normal processing
        render :action => "login"  
      else
        if not session[:user_id].nil?
          redirect_to :controller => "patients", :action => "index"
        else
          # set session variables
          login_user = User.find(:first, :conditions => { :email_address => cookies[:login]})
          if login_user.nil?
            # normal processing
            render :action => "login"  
          else
            set_session_variables(login_user)
            redirect_to :controller => "patients", :action => "index"
          end
        end
      end
    end
  end
  
  def logout
    session[:user_id] = nil
    session[:hospice_id] = nil
    cookies[:login] = nil
    redirect_to :controller => "login", :action => "login"
  end
  
  private
    def set_session_variables(login_user)
      session[:user_id] = login_user.email_address
      session[:hospice_id] = login_user.hospice_id
      session[:user_name] = login_user.name
      session[:is_admin] = login_user.is_admin
      session[:hospice_name] = Hospice.find(:first, :conditions => {:id => login_user.id}).hospice_name
    end
end
